/*
 * Copyright (C) 2010 The Android Open Source Project 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package com.freeforall;

import android.os.Handler;
import android.util.Log;

/**
 * Holds the game grid and transfers pieces from cell to cell.
 * @author Erik Buchholz
 * @author Mike Peterson
 */
public class Game implements Runnable{

	public static int GRID_SIZE = 7;
	
	public static final Cell[][] CELL_GRID = new Cell[GRID_SIZE][GRID_SIZE];
	private int[][] colorGrid;
	private Object pauseObject;
	
	/** Instantiate the color grid. */
	public Game(Handler textHandler, Object pauseObject){
		colorGrid = new int[GRID_SIZE][GRID_SIZE];
		init(textHandler);
		this.pauseObject = pauseObject;
	}
	
	/** Initialize the grids. */
	private void init(Handler textHandler){
		for (int y = 0; y < GRID_SIZE; y++){
			for (int x = 0; x < GRID_SIZE; x++){
				Cell cell = new Cell(textHandler);
				Game.CELL_GRID[y][x] = cell;
				colorGrid[y][x] = cell.getColor();
			}
		}
		
	}
	
	/** Constantly update color grid. */
	public void run(){
		while(!GameParams.getInstance().exiting){
			if (GameParams.getInstance().leaving){
				synchronized (pauseObject){
					try{
						pauseObject.wait();
					}
					catch(InterruptedException e){
						// this should not happen
						Log.e("FreeForAll", "Piece Interrupted.");
					}
				}
			}
			updateColors();
		}
	}
	
	/** Refresh the color grid. */
	private void updateColors(){
		for (int y = 0; y < GRID_SIZE; y++){
			for (int x = 0; x < GRID_SIZE; x++){
				colorGrid[y][x] = Game.CELL_GRID[y][x].getColor();
			}
		}
	}
	
	/** Gets a copy of the color grid. */
	public int[][] getColorGrid(){
		return colorGrid.clone();
	}
}
